package guda.house.biz.impl;

import java.util.ArrayList;
import java.util.List;

import guda.house.biz.form.OwnerSearchForm;
import guda.house.biz.form.bill.BatchNoticeBillForm;
import guda.house.biz.form.village.OwnerEditForm;
import guda.house.biz.form.village.OwnerForm;
import guda.house.biz.query.*;
import guda.house.biz.security.AuthUser;
import guda.house.biz.util.Transform;
import guda.house.biz.util.TransformHelper;
import guda.house.dal.dao.*;
import guda.house.dal.dataobject.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import guda.house.biz.OwnerBiz;
import guda.grape.autogen.common.page.BaseQuery;
import guda.grape.autogen.common.page.BizResult;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.StringUtils;

public class OwnerBizImpl implements OwnerBiz {

    private final static Logger logger = LoggerFactory.getLogger(OwnerBizImpl.class);

    @Autowired
    private OwnerDAO ownerDAO;
    @Autowired
    private BuildingDAO buildingDAO;
    @Autowired
    private UnitDAO unitDAO;
    @Autowired
    private SuiteDAO suiteDAO;
    @Autowired
    private ContactDAO contactDAO;
    @Autowired
    private RenderDAO renderDAO;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @Autowired
    private VillageDAO villageDAO;

    public BizResult detail(long id) {
        BizResult bizResult = new BizResult();
        try {
            OwnerDO ownerDO = ownerDAO.getOwnerById(id);
            bizResult.data.put("ownerDO", ownerDO);
            bizResult.success = true;
        } catch (Exception e) {
            logger.error("query Owner error", e);
        }
        return bizResult;
    }

    public BizResult list(OwnerQuery ownerQuery) {
        BizResult bizResult = new BizResult();
        try {
            getSuiteIdList(ownerQuery);
            int totalCount = ownerDAO.countForPage(ownerQuery);
            ownerQuery.setTotalCount(totalCount);
            List<OwnerDO> ownerList = ownerDAO.selectForPage(ownerQuery);
            bizResult.data.put("ownerList", ownerList);
            bizResult.data.put("query", ownerQuery);
            bizResult.success = true;
        } catch (Exception e) {
            logger.error("view Owner list error", e);
        }
        return bizResult;
    }

    private void getSuiteIdList(OwnerQuery ownerQuery) {
        List<Long> suiteIdList = new ArrayList<Long>();
        if (ownerQuery.getSuiteId() != null) {
           return;
        }
        if (ownerQuery.getUnitId() != null) {
            SuiteQuery suiteQuery = new SuiteQuery();
            suiteQuery.setUnitId(ownerQuery.getUnitId());
            suiteQuery.setPageSize(1000);
            List<SuiteDO> suiteDOs = suiteDAO.selectForPage(suiteQuery);
            suiteIdList = TransformHelper.transform(suiteDOs, new Transform<SuiteDO, Long>() {
                @Override
                public Long transform(SuiteDO object) {
                    return object.getSuiteId();
                }
            });
            ownerQuery.setSuiteIdList(suiteIdList);
        }
        if (ownerQuery.getBuildingId() != null) {
            UnitQuery unitQuery = new UnitQuery();
            unitQuery.setPageSize(1000);
            unitQuery.setBuildingId(ownerQuery.getBuildingId());
            List<UnitDO> unitDOs = unitDAO.selectForPage(unitQuery);
            List<Long> unitIdList = TransformHelper.transform(unitDOs, new Transform<UnitDO, Long>() {
                @Override
                public Long transform(UnitDO object) {
                    return object.getUnitId();
                }
            });

            SuiteQuery suiteQuery = new SuiteQuery();
            suiteQuery.setUnitIdList(unitIdList);
            suiteQuery.setPageSize(1000);
            List<SuiteDO> suiteDOs = suiteDAO.selectForPage(suiteQuery);
            suiteIdList = TransformHelper.transform(suiteDOs, new Transform<SuiteDO, Long>() {
                @Override
                public Long transform(SuiteDO object) {
                    return object.getSuiteId();
                }
            });
            ownerQuery.setSuiteIdList(suiteIdList);

        }
        if (ownerQuery.getVillageId() != null) {
            BuildingQuery buildingQuery = new BuildingQuery();
            buildingQuery.setPageSize(1000);
            buildingQuery.setVillageId(ownerQuery.getVillageId());
            List<BuildingDO> buildingDOs = buildingDAO.selectForPage(buildingQuery);
            List<Long> buildingIdList = TransformHelper.transform(buildingDOs, new Transform<BuildingDO, Long>() {
                @Override
                public Long transform(BuildingDO object) {
                    return object.getBuildingId();
                }
            });

            UnitQuery unitQuery = new UnitQuery();
            unitQuery.setPageSize(1000);
            unitQuery.setBuildingIdList(buildingIdList);
            List<UnitDO> unitDOs = unitDAO.selectForPage(unitQuery);
            List<Long> unitIdList = TransformHelper.transform(unitDOs, new Transform<UnitDO, Long>() {
                @Override
                public Long transform(UnitDO object) {
                    return object.getUnitId();
                }
            });

            SuiteQuery suiteQuery = new SuiteQuery();
            suiteQuery.setUnitIdList(unitIdList);
            suiteQuery.setPageSize(1000);
            List<SuiteDO> suiteDOs = suiteDAO.selectForPage(suiteQuery);
            suiteIdList = TransformHelper.transform(suiteDOs, new Transform<SuiteDO, Long>() {
                @Override
                public Long transform(SuiteDO object) {
                    return object.getSuiteId();
                }
            });
            ownerQuery.setSuiteIdList(suiteIdList);
        }

        List<Long> villageIdList = AuthUser.getCurrentUser().getVillageIdList();
        BuildingQuery buildingQuery = new BuildingQuery();
        buildingQuery.setPageSize(1000);
        buildingQuery.setVillageIdList(villageIdList);
        List<BuildingDO> buildingDOs = buildingDAO.selectForPage(buildingQuery);
        List<Long> buildingIdList = TransformHelper.transform(buildingDOs, new Transform<BuildingDO, Long>() {
            @Override
            public Long transform(BuildingDO object) {
                return object.getBuildingId();
            }
        });

        UnitQuery unitQuery = new UnitQuery();
        unitQuery.setPageSize(1000);
        unitQuery.setBuildingIdList(buildingIdList);
        List<UnitDO> unitDOs = unitDAO.selectForPage(unitQuery);
        List<Long> unitIdList = TransformHelper.transform(unitDOs, new Transform<UnitDO, Long>() {
            @Override
            public Long transform(UnitDO object) {
                return object.getUnitId();
            }
        });

        SuiteQuery suiteQuery = new SuiteQuery();
        suiteQuery.setUnitIdList(unitIdList);
        suiteQuery.setPageSize(1000);
        List<SuiteDO> suiteDOs = suiteDAO.selectForPage(suiteQuery);
        suiteIdList = TransformHelper.transform(suiteDOs, new Transform<SuiteDO, Long>() {
            @Override
            public Long transform(SuiteDO object) {
                return object.getSuiteId();
            }
        });
        ownerQuery.setSuiteIdList(suiteIdList);
    }

    public BizResult delete(long id) {
        BizResult bizResult = new BizResult();
        try {
            ownerDAO.delOwnerById(id);
            bizResult.success = true;
        } catch (Exception e) {
            logger.error("delete owner error", e);
        }
        return bizResult;
    }

    public BizResult create(final OwnerForm ownerForm) {
        final BizResult bizResult = new BizResult();
        try {
            final OwnerDO ownerDO = ownerForm.toDO();
            transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                @Override
                protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                    long id = ownerDAO.insert(ownerDO);
                    if (StringUtils.hasText(ownerForm.getRentName1())|| StringUtils.hasText(ownerForm.getRentPhone1() )) {
                        RenderDO renderDO = new RenderDO();
                        renderDO.setSuiteId(ownerForm.getSuiteId());
                        renderDO.setPhone(ownerForm.getRentPhone1());
                        renderDO.setRenderName(ownerForm.getRentName1());
                        renderDAO.insert(renderDO);
                    }
                    if (StringUtils.hasText(ownerForm.getRentName2())|| StringUtils.hasText(ownerForm.getRentPhone2())) {
                        RenderDO renderDO = new RenderDO();
                        renderDO.setSuiteId(ownerForm.getSuiteId());
                        renderDO.setPhone(ownerForm.getRentPhone2());
                        renderDO.setRenderName(ownerForm.getRentName2());
                        renderDAO.insert(renderDO);
                    }
                    if (StringUtils.hasText(ownerForm.getContactName1() )) {
                        ContactDO contactDO = new ContactDO();
                        contactDO.setSuiteId(ownerForm.getSuiteId());
                        contactDO.setPhone(ownerForm.getContactPhone1());
                        contactDO.setUserName(ownerForm.getContactName1());
                        contactDO.setRelation(ownerForm.getContactRelation1());
                        contactDAO.insert(contactDO);
                    }
                    if (StringUtils.hasText(ownerForm.getContactName2() )) {
                        ContactDO contactDO = new ContactDO();
                        contactDO.setSuiteId(ownerForm.getSuiteId());
                        contactDO.setPhone(ownerForm.getContactPhone2());
                        contactDO.setUserName(ownerForm.getContactName2());
                        contactDO.setRelation(ownerForm.getContactRelation2());
                        contactDAO.insert(contactDO);
                    }
                    bizResult.data.put("id", id);
                }
            });


            bizResult.success = true;
        } catch (Exception e) {
            logger.error("create Owner error", e);
        }
        return bizResult;
    }

    @Override
    public BizResult update(final OwnerEditForm ownerEditForm) {
        BizResult bizResult = new BizResult();
        try {
            transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                @Override
                protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                    ownerDAO.updateByIdSelective(ownerEditForm.toDO());
                    renderDAO.delRenderBySuiteId(ownerEditForm.getSuiteId());
                    contactDAO.delContactBySuiteId(ownerEditForm.getSuiteId());
                    if (StringUtils.hasText(ownerEditForm.getRentName1())|| StringUtils.hasText(ownerEditForm.getRentPhone1() )) {
                        RenderDO renderDO = new RenderDO();
                        renderDO.setSuiteId(ownerEditForm.getSuiteId());
                        renderDO.setPhone(ownerEditForm.getRentPhone1());
                        renderDO.setRenderName(ownerEditForm.getRentName1());
                        renderDAO.insert(renderDO);
                    }
                    if (StringUtils.hasText(ownerEditForm.getRentName2())|| StringUtils.hasText(ownerEditForm.getRentPhone2())) {
                        RenderDO renderDO = new RenderDO();
                        renderDO.setSuiteId(ownerEditForm.getSuiteId());
                        renderDO.setPhone(ownerEditForm.getRentPhone2());
                        renderDO.setRenderName(ownerEditForm.getRentName2());
                        renderDAO.insert(renderDO);
                    }
                    if (ownerEditForm.getContactName1() != null) {
                        ContactDO contactDO = new ContactDO();
                        contactDO.setSuiteId(ownerEditForm.getSuiteId());
                        contactDO.setPhone(ownerEditForm.getContactPhone1());
                        contactDO.setUserName(ownerEditForm.getContactName1());
                        contactDO.setRelation(ownerEditForm.getContactRelation1());
                        contactDAO.insert(contactDO);
                    }
                    if (ownerEditForm.getContactName2() != null) {
                        ContactDO contactDO = new ContactDO();
                        contactDO.setSuiteId(ownerEditForm.getSuiteId());
                        contactDO.setPhone(ownerEditForm.getContactPhone2());
                        contactDO.setUserName(ownerEditForm.getContactName2());
                        contactDO.setRelation(ownerEditForm.getContactRelation2());
                        contactDAO.insert(contactDO);
                    }
                }
            });

            bizResult.success = true;
        } catch (Exception e) {
            logger.error("update Owner error", e);
        }
        return bizResult;
    }

    @Override
    public BizResult queryForCreateReset(Long villageId, Long buildingId, Long unitId) {
        BizResult bizResult = new BizResult();
        BuildingQuery buildingQuery = new BuildingQuery();
        buildingQuery.setVillageId(buildingId);
        buildingQuery.setPageSize(10000);
        List<BuildingDO> buildingDOs = buildingDAO.selectForPage(buildingQuery);
        bizResult.data.put("buildingList", buildingDOs);

        UnitQuery unitQuery = new UnitQuery();
        unitQuery.setBuildingId(buildingId);
        unitQuery.setPageSize(10000);
        List<UnitDO> unitDOs = unitDAO.selectForPage(unitQuery);
        bizResult.data.put("unitList", unitDOs);

        SuiteQuery suiteQuery = new SuiteQuery();
        suiteQuery.setPageSize(10000);
        suiteQuery.setUnitId(unitId);
        List<SuiteDO> suiteDOs = suiteDAO.selectForPage(suiteQuery);
        bizResult.data.put("suiteList", suiteDOs);
        bizResult.success = true;
        return bizResult;
    }

    @Override
    public BizResult queryForEdit(Long suiteId) {
        BizResult bizResult = new BizResult();
        SuiteDO suiteById = suiteDAO.getSuiteById(suiteId);
        UnitDO unitById = unitDAO.getUnitById(suiteById.getUnitId());
        BuildingDO buildingDO = buildingDAO.getBuildingById(unitById.getBuildingId());

        bizResult.data.put("suiteDO", suiteById);
        bizResult.data.put("unitDO", unitById);
        bizResult.data.put("buildingDO", buildingDO);


        BuildingQuery buildingQuery = new BuildingQuery();
        buildingQuery.setPageSize(10000);
        buildingQuery.setVillageId(buildingDO.getVillageId());
        List<BuildingDO> buildingDOs = buildingDAO.selectForPage(buildingQuery);
        bizResult.data.put("buildingList", buildingDOs);

        UnitQuery unitQuery = new UnitQuery();
        unitQuery.setPageSize(10000);
        unitQuery.setBuildingId(buildingDO.getBuildingId());
        List<UnitDO> unitDOs = unitDAO.selectForPage(unitQuery);
        bizResult.data.put("unitList", unitDOs);

        SuiteQuery suiteQuery = new SuiteQuery();
        suiteQuery.setPageSize(10000);
        suiteQuery.setUnitId(unitById.getUnitId());
        List<SuiteDO> suiteDOs = suiteDAO.selectForPage(suiteQuery);
        bizResult.data.put("suiteList", suiteDOs);

        //查询租客，紧急联系人信息
        ContactQuery contactQuery = new ContactQuery();
        contactQuery.setSuiteId(suiteId);
        List<ContactDO> contactDOs = contactDAO.selectForPage(contactQuery);
        bizResult.data.put("contactList", contactDOs);
        RenderQuery renderQuery = new RenderQuery();
        renderQuery.setSuiteId(suiteId);
        List<RenderDO> renderDOList = renderDAO.selectForPage(renderQuery);
        bizResult.data.put("renderList",renderDOList);

        bizResult.success = true;
        return bizResult;
    }

    @Override
    public BizResult initSearchForm(OwnerSearchForm ownerSearchForm) {
        BizResult bizResult = new BizResult();
        if (ownerSearchForm.getVillageId() == null) {
            bizResult.success = true;
            return bizResult;
        }
        BuildingQuery buildingQuery = new BuildingQuery();
        buildingQuery.setPageSize(10000);
        buildingQuery.setVillageId(ownerSearchForm.getVillageId());
        List<BuildingDO> buildingDOs = buildingDAO.selectForPage(buildingQuery);
        bizResult.data.put("buildingList", buildingDOs);
        if (ownerSearchForm.getBuildingId() == null) {
            bizResult.success = true;
            return bizResult;
        }
        UnitQuery unitQuery = new UnitQuery();
        unitQuery.setPageSize(10000);
        unitQuery.setBuildingId(ownerSearchForm.getBuildingId());
        List<UnitDO> unitDOs = unitDAO.selectForPage(unitQuery);
        bizResult.data.put("unitList", unitDOs);

        if (ownerSearchForm.getUnitId() == null) {
            bizResult.success = true;
            return bizResult;
        }

        SuiteQuery suiteQuery = new SuiteQuery();
        suiteQuery.setPageSize(10000);
        suiteQuery.setUnitId(ownerSearchForm.getUnitId());
        List<SuiteDO> suiteDOs = suiteDAO.selectForPage(suiteQuery);
        bizResult.data.put("suiteList", suiteDOs);
        bizResult.success=true;
        return bizResult;
    }

    @Override
    public BizResult detailWithSuiteId(long suiteId) {
        BizResult bizResult = new BizResult();
        OwnerQuery ownerQuery = new OwnerQuery();
        ownerQuery.setSuiteId(suiteId);
        List<OwnerDO> ownerDOs = ownerDAO.selectForPage(ownerQuery);
        bizResult.data.put("ownerDOList",ownerDOs);

        SuiteDO suiteById = suiteDAO.getSuiteById(suiteId);
        UnitDO unitById = unitDAO.getUnitById(suiteById.getUnitId());
        BuildingDO buildingDO = buildingDAO.getBuildingById(unitById.getBuildingId());

        bizResult.data.put("suiteDO", suiteById);
        bizResult.data.put("unitDO", unitById);
        bizResult.data.put("buildingDO", buildingDO);
        bizResult.data.put("villageDO", villageDAO.getVillageById(buildingDO.getVillageId()));



        //查询租客，紧急联系人信息
        ContactQuery contactQuery = new ContactQuery();
        contactQuery.setSuiteId(suiteId);
        List<ContactDO> contactDOs = contactDAO.selectForPage(contactQuery);
        bizResult.data.put("contactList", contactDOs);
        RenderQuery renderQuery = new RenderQuery();
        renderQuery.setSuiteId(suiteId);
        List<RenderDO> renderDOList = renderDAO.selectForPage(renderQuery);
        bizResult.data.put("renderList",renderDOList);
        bizResult.success = true;
        return bizResult;
    }


}
